package com.fjwt.gz.service.activity.coupon.notify;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.coupon.hkpay.HkpayCouponWriteNotifyService;
import com.fjwt.gz.db.entity.AwardCouponNotifyEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.entity.PayOrderEntity;
import com.fjwt.gz.interfaces.ChannelCouponWriteService;
import com.fjwt.gz.service.impl.AwardCouponNotifyService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.PayOrderService;
import com.fjwt.gz.service.impl.ScoreRecordTotalService;
import com.fjwt.gz.service.activity.BaseActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class HkpayCouponWriteService implements ChannelCouponWriteService {

    private static final Logger hkPayLogger = LoggerFactory.getLogger("hkPay");

    @Autowired
    private AwardCouponNotifyService awardCouponNotifyService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ScoreRecordTotalService scoreRecordService;
    @Autowired
    private HkpayCouponWriteNotifyService hkpayCouponWriteNotifyService;

    private static String logPrefix = "海科卡券核销回调:";

    @Override
    public String addNotifyRecord(Map<String, Object> requestMap) {

        hkPayLogger.info(logPrefix + "添加回调信息记录进来的参数是：{}", JSONUtil.toJsonStr(requestMap));
        Date date = new Date();
        AwardCouponNotifyEntity couponNotifyEntity = new AwardCouponNotifyEntity();

        JSONObject reqJson = JSONObject.parseObject(MapUtil.getStr(requestMap, "req"));
        if (ObjectUtils.isEmpty(reqJson) || ObjectUtils.isEmpty(reqJson.getJSONObject("data"))) {
            hkPayLogger.info("{}，推送参数为空", logPrefix);
            return "FAIL";
        }
        JSONObject data = reqJson.getJSONObject("data");
        hkPayLogger.info(logPrefix + "data:{}", JSONUtil.toJsonStr(data));
        String couponThirdId = data.getString("couponId");
        hkPayLogger.info(logPrefix + "三方卡券ID:{}", couponThirdId);

        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponThirdId);
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);
        if (ObjectUtil.isEmpty(fansAwardEntity)) {
            hkPayLogger.info("卡券ID：{}，此卡券不是营销平台创建，直接返回，不记录数据库", couponThirdId);
            return "FAIL";
        }

        if ("USED".equals(data.getString("status"))) {
            couponNotifyEntity.setNotifyState(0);//已核销
        } else {
            couponNotifyEntity.setNotifyState(1);//未核销
        }
        couponNotifyEntity.setCouponThirdId(couponThirdId);
        couponNotifyEntity.setIfcode("hkpay");
        couponNotifyEntity.setState(1);//回调进来的都是状态1未同步
        couponNotifyEntity.setNotifyJson(JSONUtil.toJsonStr(requestMap));
        couponNotifyEntity.setCreatedAt(date);
        couponNotifyEntity.setUpdatedAt(date);
        couponNotifyEntity.setSourceType(1);
        hkPayLogger.info(logPrefix + "添加回调信息记录:{}", JSONUtil.toJsonStr(couponNotifyEntity));
        boolean save = awardCouponNotifyService.save(couponNotifyEntity);
        if (save) {
            return "SUCCESS";
        } else {
            return "FAIL";
        }
    }

    @Override
    public Map<String, Object> paraseParamters(HttpServletRequest request) throws IOException {
        return hkpayCouponWriteNotifyService.paraseParamters(request, null);
    }

    @Override
    public void couponDoNotice(AwardCouponNotifyEntity couponNotifyEntity) throws Exception {
        hkPayLogger.info(logPrefix + "处理逻辑进来的参数是：{}", JSONUtil.toJsonStr(couponNotifyEntity));
        //通过卡券三方id是否存在，如不存在，更新回调记录表，添加备注
        LambdaQueryWrapper<FansAwardEntity> fansAwardGw = FansAwardEntity.gw();
        fansAwardGw.eq(FansAwardEntity::getCouponThirdId, couponNotifyEntity.getCouponThirdId());
        FansAwardEntity fansAwardEntity = fansAwardService.getBaseMapper().selectOne(fansAwardGw);

        if (ObjectUtil.isNotEmpty(fansAwardEntity)) {
            if (fansAwardEntity.getState() == 1) {
                //卡券状态已更改
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("此订单已经推送过");
                hkPayLogger.info(logPrefix + "处理逻辑,此卡券此订单已经推送过,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            } else {
                // 处理卡券核销是否进行奖励积分
                scoreRecordService.couponWriteSendScore(fansAwardEntity);
                //是卡券营销平台创建,卡券核销后的处理
                hkPayLogger.info(logPrefix + "extraJson:{}", fansAwardEntity.getExtraJson());
                JSONObject extraJson = JSONObject.parseObject(fansAwardEntity.getExtraJson());
                if (extraJson != null && fansAwardEntity.getExtraJson().contains("templateNo")) {
                    String templateNo = extraJson.getString("templateNo");
                    BaseActivityService activityService = SpringBeansUtil.getBean(templateNo + "Service", BaseActivityService.class);
                    // 支付通道接口实现不存在
                    if (activityService == null) {
                        hkPayLogger.info(templateNo + "Service,接口不存在");
                        throw new BizException(templateNo + "Service,接口不存在");
                    }
                    JSONObject json = JSONObject.parseObject(JSONUtil.toJsonStr(fansAwardEntity));
                    activityService.run(json);
                }
                FansAwardEntity fansAwardEntityUpdate = new FansAwardEntity();
                fansAwardEntityUpdate.setFansAwardId(fansAwardEntity.getFansAwardId());
                fansAwardEntityUpdate.setState(1);
                if (StringUtils.isNotEmpty(couponNotifyEntity.getNotifyJson())) {
                    JSONObject notifyJson = JSONObject.parseObject(couponNotifyEntity.getNotifyJson());
                    JSONObject reqJosn = JSONObject.parseObject(notifyJson.getString("req"));
                    hkPayLogger.info("海科核销回调的参数：{}", JSONUtil.toJsonStr(reqJosn));
                    String data = reqJosn.getString("data");
                    JSONObject dataJson = JSONObject.parseObject(data);
                    String consumeInformation = dataJson.getString("consumeInformation");
                    JSONObject consumeInformationJosn = JSONObject.parseObject(consumeInformation);
                    Date consumeTime = consumeInformationJosn.getObject("consumeTime", Date.class);
                    fansAwardEntityUpdate.setWriteTime(consumeTime);
                } else {
                    fansAwardEntityUpdate.setWriteTime(new Date());
                }

                //如果能通过三方卡券id查询到订单，则添加商户号，（此订单核销属于新平台的订单，如果没有则表示是老平台的订单，就没有商户号）
                LambdaQueryWrapper<PayOrderEntity> payOrderGw = PayOrderEntity.gw();
                payOrderGw.eq(PayOrderEntity::getCouponThirdId, fansAwardEntity.getCouponThirdId());
                PayOrderEntity payOrderEntity = payOrderService.getBaseMapper().selectOne(payOrderGw);
                if (ObjectUtil.isNotEmpty(payOrderEntity)) {
                    fansAwardEntityUpdate.setMchNo(payOrderEntity.getMchNo());
                }
                hkPayLogger.info(logPrefix + "此卡券核销更新数据，更新数据的信息是：{}", JSONUtil.toJsonStr(fansAwardEntityUpdate));
                fansAwardService.updateById(fansAwardEntityUpdate);

                //更新回调数据状态
                AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
                couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
                couponNotifyUpdate.setState(2);
                couponNotifyUpdate.setRemark("核销成功");
                hkPayLogger.info(logPrefix + "核销成功,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
                awardCouponNotifyService.updateById(couponNotifyUpdate);
            }
        } else {
            //卡券不是营销平台创建
            AwardCouponNotifyEntity couponNotifyUpdate = new AwardCouponNotifyEntity();
            couponNotifyUpdate.setCouponNotifyId(couponNotifyEntity.getCouponNotifyId());
            couponNotifyUpdate.setState(2);
            couponNotifyUpdate.setRemark("此卡券不是营销平台创建");
            hkPayLogger.info(logPrefix + "处理逻辑,此卡券不是营销平台创建,更新的数据是：{}", JSONUtil.toJsonStr(couponNotifyUpdate));
            awardCouponNotifyService.updateById(couponNotifyUpdate);
        }
    }

}
